// pages/home/index.js
const global = getApp().globalData
import {
  getProducts,
  getProductDevices,
  addProduct,
  saveMyProduct,
  loadMyProducts,
  getAppDevices,
  addDevice,
  delDevice
} from '../../utils/api.js'
import {
  stringToBuffer,
  byteToString,
  ab2hex
} from '../../utils/util.js'
var deviceCreate = require('../../jsons/reqJson/deviceCreate.js');
var nfcAd = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showSelectProdect: false,
    showAddDevice: false,
    selectedProduct: '',
    login: wx.getStorageSync('account') || '',
    devices: global.devices || [],
    product_id: '',
    device_id: '',
    device_name: '',
    wifiSSID: '',
    wifiPwd: '',
    showNfc: false,
    showAddProdcut: false,
    newProductName: '',
    setNfcText: '请把手机贴近开发板NFC区域',
    btnNfcText: '取消',
    myProducts: [],
    // 列表
    list: [{
        id: 'Ah1111101',
        title: "flower1",
        type: '设备离线',
        url: '../../images/flower.png'
      },
      {
        id: 'Ah1111102',
        title: "flower2",
        type: '设备未激活',
        url: '../../images/flower.png'
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadAllDevices();
    this.loadMyProducts()

  },
  loadAllDevices: function (func) {
    if (global.token && global.project_id) {
      getAppDevices({
        project_id: global.project_id,
        app_id: global.app_id
      }).then(res => {
        var devices = res.devices
        for (const d of devices) {
          var p = d.product_name.split('_')
          if (p.length == 1) p[0] = 'icon_intro'
          d.url = `../../images/${p[p.length - 1].toLowerCase()}.png`
        }
        this.setData({
          devices: devices
        })
        if (func) func(devices)
      })
    }
  },
  toDelDevice: function (e) {
    let ds = e.currentTarget.dataset.device
    wx.showModal({
      title: '提示',
      content: `设备[${ds.device_name}]将被删除?`,
      success: (res) => {
        if (res.confirm) {
          delDevice({
            device_id: ds.device_id
          }).then(res => {
            this.loadAllDevices()
          })
        } else if (res.cancel) {

        }
      }
    })


  },

  toDetail: function (e) {
    let ds = e.currentTarget.dataset.device
    console.log(e);
    if (ds.status == "ONLINE") {
      let p = ds.product_name.split('_')
      let page = p[p.length - 1].toLowerCase()
      if ("agriculture,autowater,smoke,familyassistant,cabin".indexOf(page) < 0)
        page = 'custom'
      wx.navigateTo({
        url: `../device/${page}?deviceId=${ds.device_id}&dname=${ds.device_name}&product_name=${ds.product_name}`,
      })
    } else {
      wx.showToast({
        title: '当前设备不在线',
        icon: 'error'
      })
    }
  },
  toLogin: function () {
    wx.switchTab({
      url: '../mine/mine',
    })
  },
  toAddDevice: function () {
    this.setData({
      showSelectProdect: true
    });
  },
  checkProduct: function (product_name, call) {
    getProducts({
      project_id: global.project_id,
      app_id: global.app_id
    }).then(res => {
      let product = null
      var products = res.products || [];
      for (let item of products) {
        if (item.name == product_name) {
          product = item
          break;
        }
      }
      // call(product)
      if (product == null) {
        var productTeplate = require(`../../jsons/servicetype-capability/${this.data.selectedProduct}.js`);
        console.log('product template', productTeplate.template);

        productTeplate.template.app_id = global.app_id
        var params = {
          project_id: global.project_id,
          productCreateJson: productTeplate.template
        }
        console.log(params);
        addProduct(params).then(res => {
          call(res) //返回产品              
        })
      } else {
        call(product)
      }
    })
  },
  addOrGetDevice: function (func) {
    //检查输入
    var json = deviceCreate.deviceCreateJson;
    json.node_id = this.data.device_name
    json.device_name = this.data.device_name
    // json.project_id = global.project_id
    json.product_id = global.product_id
    json.app_id = global.app_id

    //产品是否存在
    this.checkProduct(this.data.selectedProduct, product => {
      //检查设备，创建设备
      var has = this.data.devices.filter((x) => {
        return x.device_name == this.data.device_name;
      });
      if (has == false) {
        var params = {
          "deviceCreateJson": {
            "node_id": this.data.device_name,
            "device_name": this.data.device_name,
            "product_id": product.product_id,
            "app_id": product.app_id,
            "description": ""
          },
          "project_id": global.project_id
        }
        addDevice(params).then(device => {
          if (device.device_id) {
            this.setData({
              showAddDevice: false
            })
            func({
              device_id: device.device_id,
              secret: device.auth_info.secret
            }, {
              ssid: this.data.wifiSSID,
              pwd: this.data.wifiPwd
            })
          } else {
            wx.showModal({
              title: '创建设备失败',
              content: `${res.error_msg}`,
              showCancel: false
            })
          }
        })
      } else {
        func(null, {
          ssid: this.data.wifiSSID,
          pwd: this.data.wifiPwd
        })
      }
    })
  },
  closeNfc: function () {
    this.setData({
      showNfc: false
    })
    this.loadAllDevices()
  },
  closeSelect: function () {
    this.setData({
      showSelectProdect: false,
    });
  },
  closeInput: function () {
    this.setData({
      showAddProdcut: false,
      showAddDevice: false,
      device_name: '',
      wifiPwd: '',
    });
  },
  selectProduct: function (e) {
    // wifi
    wx.startWifi({
      success: (res) => {
        wx.getConnectedWifi({
          success: (result) => {
            console.log('wifi res', result);
            this.setData({
              wifiSSID: result.wifi.SSID
            })
          }
        })
      },
    })
    this.setData({
      showAddDevice: true,
      setNfcText: '请把手机贴近开发板NFC区域',
      btnNfcText: '取消',
      selectedProduct: e.currentTarget.dataset.product
    })
  },
  toAddProduct: function () {
    this.setData({
      showAddProdcut: true
    })
  },
  addMyProduct: function () {

  },
  selectProfile: function () {
    if (!this.data.newProductName) {
      wx.showModal({
        title: '提示',
        content: `请填写新产品的名称`,
        showCancel: false
      })
      return
    }
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success: (res) => {
        console.log(res.tempFiles)
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles[0]
        var file = `${global.openid}_${this.data.newProductName}`
        // console.log('file name', file);
        wx.uploadFile({
          filePath: tempFilePaths.path,
          name: file,
          url: `${global.MyIoTDomain}/api/Bearpi/UpFile`,
          success: (res) => {
            var sevice = JSON.parse(JSON.parse(res.data).data);
            // console.log(sevice);
            var template = {
              "name": this.data.newProductName,
              "device_type": "Custom",
              "protocol_type": "MQTT",
              "data_format": "json",
              "service_capabilities": sevice.service_capabilities
            }
            // console.log(template);
            template.app_id = global.app_id
            var params = {
              project_id: global.project_id,
              productCreateJson: template
            }
            addProduct(params).then(res => {
              console.log('add product', res);
              if (res.product_id) {
                saveMyProduct({
                  'productName': this.data.newProductName,
                  'openid': global.openid,
                  'profile': file + ".json"
                }).then(res => {
                  console.log('save product', res);
                  this.loadMyProducts()
                  this.setData({
                    showAddProdcut: false,
                    newProductName: ''
                  })
                })
                wx.showModal({
                  title: '提示',
                  content: `产品${this.data.newProductName}创建成功`,
                  showCancel: false
                })
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.error_msg,
                  showCancel: false
                })
              }
            })

          },
          complete: (res) => {
            // console.log('upload complete ', JSON.parse(JSON.parse(res.data).data));
          }
        })
      }
    })
  },
  loadMyProducts: function () {
    loadMyProducts({
      'openid': global.openid
    }).then(res => {
      console.log('res', res);
      this.setData({
        myProducts: res.list
      })
    }), err => {
      console.log('err', err);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // if (this.nfcAd)
    //   this.nfcAd.close()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadAllDevices(res => {
      wx.stopPullDownRefresh({
        success: (res) => {},
      })
    })

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //新设备发送NFC
  addDevice2NFC: function () {
    const nfc = wx.getNFCAdapter()
    var that = this
    that.nfcAd = nfc
    console.log('NFC:', nfc);
    var old_device = null;
    nfc.onDiscovered(res => {
      console.log("onDiscovered res=>", res);
      if (res.messages) {
        let cordsArray = res.messages[0].records;
        cordsArray.find((item) => {
          let payload = byteToString(new Uint8Array(item.payload))
          let id = byteToString(new Uint8Array(item.id))
          let type = byteToString(new Uint8Array(item.type))
          console.log('payload', payload, id, type);
          try {
            payload = JSON.parse(payload.split('en')[1])
            console.log('payload', payload);
          } catch (error) {
            console.log("开发板NFC无内容");
          }
          if (payload && payload.device_id && payload.secret) {
            old_device = {
              device_id: payload.device_id,
              secret: payload.secret
            }
          }
        })
      }
      if (res.techs.includes(nfc.tech.ndef)) {
        const ndef = nfc.getNdef()
        ndef.connect({
          success: (res) => {
            nfc.stopDiscovery();
            that.addOrGetDevice((device, wifi) => {
              device = device || old_device
              console.log(device);
              var payload = JSON.stringify({
                "product": that.data.selectedProduct,
                "device_id": device.device_id,
                "secret": device.secret,
                "ssid": wifi.ssid,
                "pwd": wifi.pwd
              })
              let records = [{
                id: new ArrayBuffer(),
                payload: stringToBuffer(payload, "02,65,6E"),
                type: stringToBuffer('T'),
                tnf: 1
              }]
              ndef.writeNdefMessage({
                records: records,
                fail: (res) => {
                  console.log('writeNdefMessage fail res:', res)
                  that.setData({
                    setNfcText: '配置失败',
                    btnNfcText: '确定'
                  })
                },
                success: (res) => {
                  console.log('writeNdefMessage success res:', res)
                  that.setData({
                    setNfcText: '配置成功，请重启开发板',
                    btnNfcText: '确定'
                  })
                },
                complete: (res) => {
                  nfc.stopDiscovery();
                }
              })
            })
          },
          fail: (res) => {
            console.log('connect fail res', res);
            nfc.stopDiscovery();
          }
        })
        return
      }

      if (res.techs.includes(nfc.tech.nfcA)) {
        const nfcA = nfc.getNFCA()
        nfcA.transceive({
          data: new ArrayBuffer(0),
          complete: (res) => {
            console.log('transceive res:', res)
          }
        })
        return
      }
    })
    nfc.startDiscovery({
      success: (ret) => {
        console.log('success to discover:', ret)
        that.setData({
          showNfc: true,
          showAddDevice: false
        })
      },
      fail: (err) => {
        console.log('failed to discover:', err)
        that.setData({
          setNfcText: '请打开NFC并授权'
        })
      }
    })
  },
  setNewDeviceNfc: function (device, wifi) {
    const nfc = wx.getNFCAdapter()
    var that = this
    that.nfcAd = nfc
    console.log('NFC:', nfc);

    nfc.onDiscovered(res => {
      console.log("onDiscovered res=>", res);
      if (res.messages) {
        let cordsArray = res.messages[0].records;
        cordsArray.find((item) => {
          let payload = byteToString(new Uint8Array(item.payload))
          let id = byteToString(new Uint8Array(item.id))
          let type = byteToString(new Uint8Array(item.type))
          console.log('payload', payload, id, type);
          if (!device) {
            device = {
              device_id: payload.device_id,
              secret: payload.secret
            }
          }
        })
      }
      if (!device) {
        wx.showToast({
          title: '开发版没有设备信息,请写入新设备',
        })
        return
      }
      if (res.techs.includes(nfc.tech.ndef)) {
        var payload = "en" + JSON.stringify({
          "product": that.data.selectedProduct,
          "device_id": device.device_id,
          "secret": device.secret,
          "ssid": wifi.ssid,
          "pwd": wifi.pwd
        })
        let records = [{
          id: new ArrayBuffer(),
          payload: stringToBuffer(payload),
          type: stringToBuffer('T'),
          tnf: 1
        }]
        const ndef = nfc.getNdef()
        ndef.connect({
          success: (res) => {
            nfc.stopDiscovery();
            ndef.writeNdefMessage({
              records: records,
              fail: (res) => {
                console.log('writeNdefMessage fail res:', res)
                ndef.close()
                that.setData({
                  setNfcText: '配置失败',
                  btnNfcText: '确定'
                })
              },
              success: (res) => {
                ndef.close()
                console.log('writeNdefMessage success res:', res)
                that.setData({
                  setNfcText: '配置成功，请重启开发板',
                  btnNfcText: '确定'
                })
              }
            })
          },
          complete: (res) => {
            console.log('connect res', res);
            nfc.stopDiscovery();
          }
        })
        return
      }

      if (res.techs.includes(nfc.tech.nfcA)) {
        const nfcA = nfc.getNFCA()
        nfcA.transceive({
          data: new ArrayBuffer(0),
          complete: (res) => {
            console.log('transceive res:', res)
          }
        })
        return
      }
    })
    nfc.startDiscovery({
      success: (ret) => {
        console.log('success to discover:', ret)
        that.setData({
          showNfc: true
        })
      },
      fail: (err) => {
        console.log('failed to discover:', err)
        that.setData({
          setNfcText: '请打开NFC并授权'
        })
      }
    })
  },

  setWifiNfc: function (wifi) {
    //设备信息从nfc读取，再和Wifi一起写入


  }
})